package com.lihh.rocket5.normal;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.util.List;

public class BalanceConsumer {
  public static void main(String[] args) throws MQClientException {
    // 推流的消费者
    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("balance_consumer");
    // 设置 name server 地址
    consumer.setNamesrvAddr("localhost:9876");
    // 设置集群消费模式
    consumer.setMessageModel(MessageModel.CLUSTERING);
    // 开始订阅 主题
    consumer.subscribe("order001", "*");
    // 设置 消费位置
    consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
    
    // 注册 && 回调
    consumer.registerMessageListener(new MessageListenerConcurrently() {
      @Override
      public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        try {
          for (MessageExt msg : list) {
            // 拿到主题
            String topic = msg.getTopic();
            // 拿到消息题
            String msgBody = new String(msg.getBody(), RemotingHelper.DEFAULT_CHARSET);
            // 拿到 tag
            String tags = msg.getTags();
            System.out.println("收到消息：" + " topic :" + topic + " ,tags : " + tags + " ,msg : " + msgBody);
          }
        } catch (Exception e) {
          return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
      }
    });
    
    consumer.start();
    //注销Consumer
    //consumer.shutdown();
    System.out.printf("Consumer Started.%n");
    while (true) {
    }
  }
}
